package com.jishulianmeng.util;

import java.util.Random;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;


public class SendEmailImpl {
	
	public static boolean sendEmail(EmailEntity emailEntity)
	{
		boolean flag=false;//设置标示判断路径和名称是否正确.确定是否发送附件 
		EmailAttachment attachment=null;
		if(emailEntity.getAttachFileNames()==null||"".equals(emailEntity.getAttachFileNames())||"".equals(emailEntity.getFileName()) ||emailEntity.getFileName()==null)
		{
			flag=false;
			
		}else{
			// 创建附件  
			   attachment = new EmailAttachment();  
			  attachment.setPath(emailEntity.getAttachFileNames());
			  attachment.setDisposition(EmailAttachment.ATTACHMENT);  
			  attachment.setName(emailEntity.getFileName());  //这其实是指定格式我查
			  flag=true;
		}
		  // 创建电子邮件  
		  MultiPartEmail email = new MultiPartEmail();  
		  email.setHostName(emailEntity.getServiceType());  
		  try {
			  email.addTo(emailEntity.getToAddress(), emailEntity.getToAddressName());//收件人
			  email.setFrom(emailEntity.getFromAddress(),emailEntity.getFromAddressName());//发件人信息  
			  email.setAuthentication(emailEntity.getUserName(), emailEntity.getPassword());//发件人用户和密码
			  email.setSubject(emailEntity.getSubject());  
			  email.setMsg(emailEntity.getContent());  
			  // 添加附件  
			  if(flag==true)
			  {
				  email.attach(attachment);  
			  }
			  // 发送邮件  
			  email.send(); 
			  return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		 
		return false;
	}
	/**
	 * 这是一个不带附件发送的例子
	 * @param validate
	 * @return 
	 */
	public static String  EmailSendString(String validate)
	{
		String[] emailFormat={"qq.com","163.com","sina.com","sohu.com","126.com","google.com","189.com","outlook.com"};
		for (int i = 0; i < emailFormat.length; i++) {
			if(validate.contains(emailFormat[i]))
			{
				return "smtp."+emailFormat[i].toString();
			}
		}
		return "没有你要的个格式";
	}
	public static String sendEmail(String emailAdress)
	{ 	// 创建电子邮件  
		  MultiPartEmail email = new MultiPartEmail();  
		String emailFormat= EmailSendString(emailAdress);
		if("".equals(emailFormat)||emailFormat==null)
		{
			return "";
		}else
		{
			  email.setHostName("smtp.163.com");  
			  try {
				  email.addTo(emailAdress, "");//收件人
				  email.setFrom("wds_163_sky@163.com","中国技术联盟");//发件人信息  
				  email.setAuthentication("wds_163_sky@163.com", "wds123");//发件人用户和密码
				  String validate=validate();
				  email.setMsg("恭喜你注册成功.你的验证码:"+validate);
				  // 发送邮件  
				  email.send(); 
				  return validate;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		}
		
		return "";
	}
	public static String validate()
	{
		Random rd=new Random();
		String charNum="";
		for (int i = 0; i < 6; i++) {
			charNum+=rd.nextInt(10);
		}
		return charNum;
	}
}
